package org.jackysoft.file;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Collection;
import java.util.Date;
import java.util.UUID;

import javax.annotation.Resource;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.jackysoft.data.JdbcWork;
import org.jackysoft.entity.HistoryFileItem;
import org.jackysoft.entity.ReceivedFileItem;
import org.jackysoft.entity.UploadedFileItem;
import org.jackysoft.entity.nosql.OperationLog;
import org.jackysoft.service.OperationLogService;
import org.jackysoft.util.CollectionUtils;
import org.jackysoft.util.OperationType;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.google.common.collect.Lists;

@Component
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class TranslateJDBCWorker implements JdbcWork {
	
	private OperationLogService logService;
	
	private FileType type;
	private Collection<String> fileIds;
	private Collection<String> toUsers;
	private String fromer;
	@Value("${diskBase}")
	private String diskBase;

	public static final String DATE_PATTERN="yyyy-MM-dd HH:mm:ss";
	
	public TranslateJDBCWorker() {

	}

	/**
	 * 构造jdbc函数集合
	 * 
	 * @param type
	 *            指示来源文件是本地上传还是已收文件
	 * @param fileIds
	 *            文件id集合
	 * @param toUsers
	 *            去向用户集合
	 * @param fromer
	 *            来源用户
	 * */
	public TranslateJDBCWorker(FileType type, Collection<String> fileIds,
			Collection<String> toUsers, String frommer,String diskBase) {

		CollectionUtils.notNullable(fileIds);
		CollectionUtils.notNullable(toUsers);
		this.type = type;
		this.fileIds = fileIds;
		this.toUsers = toUsers;
		this.fromer = frommer;	
		this.diskBase = diskBase;

	}

	@Override
	public void execute(Connection connection) throws SQLException {
		Session sess = this.getSessionFactory().getCurrentSession();
		switch (this.type) {
		case RECEIVED:
		case SENT:
			transReceivedFile(connection);
			sess.evict(ReceivedFileItem.class);
			break;
		case UPLOADED:
			transUploadFile(connection);
			sess.evict(UploadedFileItem.class);
			break;
		case HISTORY:
			transHistoryFile(connection);
			sess.evict(HistoryFileItem.class);
			break;
		default:
			throw new IllegalArgumentException("错误的参数 : " + this.type);

		}

	}

	private int[] transHistoryFile(Connection connection) throws SQLException{
		Statement stat = connection.createStatement();
		String dateStr = DateTime.now().toString(DATE_PATTERN);
		Collection<OperationLog> oprs = Lists.newArrayList();
		for (String fid : fileIds) {
			for (String owner : toUsers) {
				UUID uid = UUID.randomUUID();
				String id = uid.toString();
				OperationLog opr = new OperationLog();
				opr.setOprType(OperationType.User);
				opr.setCreateDate(new Date());
				opr.setName("传递文件");
				String details = fromer + "传递编号为"+fid+"的文件到"+owner;
				opr.setDetails(details);				
				String sql = 						
				String.format("insert into receivedfileitem (id, description, imgpath,realName,size,  title, deleteFlag, createTime,owner_name,fromer_name,shared,diskBase,fileType )  "
			    +"select '%s' as id, description, imgpath, realName ,size, title, deleteFlag, '%s' as createTime,'%s' as owner_name,'%s' as fromer_name,shared, '%s' as diskBase, fileType"
			    + " from HistoryFileItem where id='%s'",id,dateStr,owner,fromer,diskBase,fid);
				stat.addBatch(sql);
			    oprs.add(opr);
			}
		}
		int[] rst = stat.executeBatch();
		logService.create(oprs);
		return rst;
		
	}

	int[] transUploadFile(Connection connection) throws SQLException {
		Statement stat = connection.createStatement();
		String dateStr = DateTime.now().toString(DATE_PATTERN);
		Collection<OperationLog> oprs = Lists.newArrayList();
		for (String fid : fileIds) {
			for (String owner : toUsers) {
				UUID uid = UUID.randomUUID();
				String id = uid.toString();
				OperationLog opr = new OperationLog();
				opr.setOprType(OperationType.User);
				opr.setCreateDate(new Date());
				opr.setName("传递文件");
				String details = fromer + "传递编号为"+fid+"的文件到"+owner;
				opr.setDetails(details);				
				String sql = 						
				String.format("insert into receivedfileitem (id, description, imgpath,realName,size,  title, deleteFlag, createTime,owner_name,fromer_name,shared,diskBase,fileType )  "
			    +"select '%s' as id, description, imgpath, realName ,size, title, deleteFlag, '%s' as createTime,'%s' as owner_name,'%s' as fromer_name,shared, '%s' as diskBase, fileType"
			    + " from uploadedfileitem where id='%s'",id,dateStr,owner,fromer,diskBase,fid);
				stat.addBatch(sql);
			    oprs.add(opr);
			}
		}
		int[] rst = stat.executeBatch();
		logService.create(oprs);
		return rst;

	}

	int[] transReceivedFile(Connection connection) throws SQLException {
		Statement stat = connection.createStatement();
		String dateStr = DateTime.now().toString(DATE_PATTERN);
		Collection<OperationLog> oprs = Lists.newArrayList();
		for (String fid : fileIds) {
			for (String owner : toUsers) {
				OperationLog opr = new OperationLog();
			    opr.setOprType(OperationType.User);
				opr.setCreateDate(new Date());
				opr.setName("传递文件");
				String details = fromer + "传递编号为"+fid+"的文件到  "+owner;
				opr.setDetails(details);
				UUID uid = UUID.randomUUID();
				String id = uid.toString();
				// id = id.replaceAll("\\-", "");
				String sql = 
						String.format(
						"insert into receivedfileitem (id, description ,imgpath, realName ,size, title, deleteFlag, createTime, owner_name,fromer_name,shared,diskBase,fileType) "
						+ "select  '%s' as id, description, imgpath, realName , size, title,deleteFlag, '%s' as createTime,'%s' as owner_name,'%s' as fromer_name ,shared,'%s' as diskBase, fileType"
						+ " from receivedfileitem where id='%s'",id,dateStr,owner,fromer,diskBase,fid);
				stat.addBatch(sql);
				oprs.add(opr);
				
			}
		}
		int[] rst = stat.executeBatch();
		logService.create(oprs);
		return rst;

	}

	private SessionFactory sessionFactory;

	@Resource
	public void setSessionFactory(SessionFactory sf) {
		this.sessionFactory = sf;
	}

	@Override
	public SessionFactory getSessionFactory() {
		return this.sessionFactory;
	}

	public FileType getType() {
		return type;
	}

	public void setType(FileType type) {
		this.type = type;
	}

	public Collection<String> getFileIds() {
		
		return fileIds;
	}

	public void setFileIds(Collection<String> fileIds) {
		this.fileIds = fileIds;
	}

	public Collection<String> getToUsers() {
		return toUsers;
	}

	public void setToUsers(Collection<String> toUsers) {
		
		this.toUsers = toUsers;
	}

	public String getFromer() {
		return fromer;
	}

	public void setFromer(String fromer) {
		this.fromer = fromer;
	}

    @Resource
	public void setLogService(OperationLogService logService) {
		this.logService = logService;
	}
}
